package com.osell.selection.ui.main;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.da.lon.wang.xlg.R;
import com.osell.selection.data.entity.PageResult;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.data.network.entity.Product;
import com.osell.selection.ui.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RecommendProductsFragment extends BaseFragment {

    @BindView(R.id.vp_product)
    VerticalViewPager vp_product;

    private Unbinder mUnBinder;

    private RecommendProductPagerAdapter mAdapter;
    private List<Product> mData;
    private int mCurrentPage;
    private Observable<PageResult<Product>> mObservable;
    private Disposable mDisposable;

    private boolean mRefreshing;
    private boolean mEnd;
    private boolean mFailed;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend_products, container, false);
        mUnBinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mData = new ArrayList<>();
        mAdapter = new RecommendProductPagerAdapter(getChildFragmentManager(), mData);
        vp_product.setAdapter(mAdapter);
        vp_product.setOffscreenPageLimit(3);
        vp_product.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position == mData.size() - 1 && !mRefreshing && (!mEnd || mFailed)) {
                    createNewObservable();
                    setupContent();
                }
            }
        });

        mCurrentPage = 1;
        createNewObservable();
        setupContent();
    }

    private void createNewObservable() {
        mObservable = RestAPI.getInstance().oSellService().getCategoriesProducts(21, null, mCurrentPage)
                .map(homeInfoResponseData -> {
                    PageResult<Product> result = new PageResult<>();
                    result.page_number = mCurrentPage;
                    result.page_size = 10;
                    result.total_pages = homeInfoResponseData.data.products.size() < result.page_size ? mCurrentPage : Integer.MAX_VALUE;
                    result.elements = new ArrayList<>();
                    for (Product product : homeInfoResponseData.data.products) {
                        if (TextUtils.equals(product.type, "ad")) {
                            result.elements.add(Product.AdProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "video")) {
                            result.elements.add(Product.VideoProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "product_one")) {
                            result.elements.add(Product.OneProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "product_more")) {
                            result.elements.add(Product.MoreProduct.convertFrom(product));
                        }
                    }
                    result.total_elements = result.elements.size();
                    return result;
                })
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    private void setupContent() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        mRefreshing = true;
        mDisposable = mObservable.subscribe(pageResult -> {
            mRefreshing = false;
            mFailed = false;
            mEnd = mCurrentPage >= pageResult.total_pages;
            if (pageResult.total_pages != 0) {
                if (mCurrentPage <= pageResult.total_pages) {
                    if (mCurrentPage == 1) {
                        mData.clear();
                    }
                    mData.addAll(pageResult.elements);
                    mAdapter.notifyDataSetChanged();
                    if (mCurrentPage == 1) {
                        vp_product.setCurrentItem(0);
                        vp_product.beginFakeDrag();
                        vp_product.fakeDragBy(-1);
                        vp_product.endFakeDrag();
                    }
                    if (mCurrentPage < pageResult.total_pages) {
                        mCurrentPage++;
                    }
                }
            }
        }, throwable -> {
            mRefreshing = false;
            mFailed = true;
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        mUnBinder.unbind();
    }
}
